<template>
  <div>
    <Row>
      <!--左侧导航栏-->
      <i-col :span="hideleft?0:5" v-if="!hideleft" style="z-index: 0;background: #f1f1f1;border-right: solid 1px #d1d1d1">
        <Tree :data="tData.folderTreeData" :multiple="false" :render="renderContent"></Tree>
      </i-col>
      <!--右侧数据展示区域-->
      <i-col :span="hideleft?24:19">
        <div class="base_padding">

          <Row>
            <i-col span="24" style="text-align: center">
              <Spin fix v-if="tStatus.spinLoading" >
              <Icon type="load-c" size=18 class="demo-spin-icon-load">Loading</Icon>
            </Spin></i-col>
          </Row>

          <Row style="background: white;">
            <i-col span="8" style="text-align: left">
              <ul style="width:500px; white-space:nowrap;">
                <li @click="selectedFolderForBar(item)"
                    style="list-style:none;padding:0;margin:0;float: left;margin-left: 10px;  "
                    v-for="item in tStatus.breadcrumbList">
                  \
                  <Icon type="ios-folder-outline" style="margin-right: 3px"></Icon>
                  {{item.name}}
                </li>
              </ul>
            </i-col>
            <i-col span="16" style="text-align: right" v-if="tStatus.breadcrumbList.length > 0">
              <i-switch size="large" v-if="tStatus.showChooseSingle" v-model="tStatus.isSingle"
                        @on-change="changeIsSingle">
                <span slot="open">单选</span>
                <span slot="close">多选</span>
              </i-switch>
              <Upload :action="uploadUrl" :before-upload="beforeUpload" :data="param.uploadFolderParam" :with-credentials="false"
                      :on-success="uploadImageSuccess" :on-progress="uploadImageProgress" accept="image/png,image/jpeg,image/jpg" multiple
                      :on-error="uploadImageError" :show-upload-list="false"
                      style="display: inline-block;width:120px;">
                <Button type="primary" icon="md-cloud-upload" class="tiy_btn">
                  上传图片
                </Button>
              </Upload>
              <Button type="primary" icon="md-add" class="tiy_btn" @click="addFolder">新建文件夹
              </Button>
            </i-col>
          </Row>
          <Row>
            <i-col span="24">
              <Row style="margin-top: 1rem" :gutter="10">
                <Alert type="warning" v-if="folderList.length == 0"
                       style="height: 250px;width: 100%;text-align: center;margin-top: 10px">
                  没有文件或文件夹,请上传图片或者创建文件夹
                </Alert>
                <i-col v-for="item in folderList">
                  <Card class="item_card">
                    <!--文件夹-->
                    <div class="item_folder" v-if="'' == item.suffix"  @click="selectedFolder(item)">
                      <Icon type="ios-folder-outline" size="100"/>
                      <p>{{item.name}}</p>
                    </div>
                    <!--图片类型-->
                    <div class="item_folder" v-else  @click="clickImage(item)">
                      <div class="item_img_parent">
                        <Img :src="yunPath + item.yunKey"/>
                      </div>
                      <p>{{item.name}}.{{item.suffix}}</p>
                    </div>

                    <div class="item_select" @click="clickImage(item)"
                         v-if="tStatus.refreshChecked && isImgSelected(item)">
                       <Icon type="md-checkmark-circle"  color="#9c27b0" size="30"/>
                    </div>
<!--                    <div slot="extra">-->
<!--                      <span @click="deleteItem(item)">-->
<!--                      <Button type="text" shape="circle" size="small" icon="ios-close-circle"></Button>-->
<!--                    </span>-->
<!--                    </div>-->
                  </Card>
                </i-col>
              </Row>
              <div style="float: right;">
                <Page :total="page.total" :page-size="page.stepNumber" :current="page.currentPage"
                      @on-change="changePage"
                      @on-page-size-change="sizeChange"
                      show-sizer show-elevator/>
              </div>
            </i-col>
          </Row>
        </div>
      </i-col>
    </Row>

    <Row style="text-align: right">
      <i-col span="24">
        <Button type="text" @click="btnCancelClicked">取消</Button>
        <Button type="primary" @click="btnSureClicked">确定</Button>
      </i-col>
    </Row>

    <!--删除确认弹出框-->
    <Modal
      v-model="tStatus.modalDelete.isShow"
      title="确认删除"
      :loading="tStatus.modalDelete.isLoading"
      style="z-index:88"
      :transfer="false"
      @on-ok="webDelete">
      <p>确认删除<strong> {{tStatus.modalDelete.folder.name}}?</strong></p>
    </Modal>
    <!--新建文件夹弹出框-->
    <Modal
      v-model="tStatus.modalFolder.isShow"
      title="新建文件夹"
      :closable="false"
      :mask-closable="false"
      :loading="tStatus.modalFolder.isLoading"
      style="z-index:88"
      :transfer="false"
      @on-ok="webAdd"
    >
      <Form ref="addFolder" :model="param.folder" :rules="ruleFolder"
            class="modal_newuser_form">
        <FormItem label="文件夹名称" prop="name">
          <Input v-model.trim="param.folder.name" placeholder="请输入"
                 class="modal_form_input"></Input>
        </FormItem>
      </Form>


    </Modal>
  </div>
</template>

<!--javascript 代码-->
<script>

  import ICol from "../../../node_modules/view-design/src/components/grid/col";
  import tiyData from "./js/select/image_data"
  import {imageInit, webImageAdd, webImageDelete, webImageList, webFolderListByParentId} from "./js/select/image_funs"
  import {imageSizeModal} from "../js/commonUtils";
  import {removeSpam} from "../email/js/trashEmail/trash_fun";
  import ApiBase from "../../api/moudles/ApiBase";

  export default {
    props:{
      hideleft:{
        type:Boolean,
        default:false
      }
    },
    data(){
      return {
        page: tiyData.tPage,
        param: tiyData.tParams,
        yunPath: this.$store.getters.imgPrefix,
        tData: tiyData.tData,
        tStatus: tiyData.tStatus,
        folderList: tiyData.tData.folderList,
        uploadUrl: this.$apiImage.getUploadToOssUrl(),
        ruleFolder: tiyData.tStatus.rules,
        selectedFolderList:[],
        selectedFolderListIds:[],
        imageList: [],
        imageListLength: 0,
      }
    },
    components: {
      ICol
    },
    methods: {

      btnCancelClicked(){
        this.$emit('cancelClicked')
      },
      btnSureClicked(){
        //提示所选图片的尺寸
        let imageList = [];
        let self = this;
        this.selectedFolderList.forEach(function (item) {
          let name = item.yunKey.substring(item.yunKey.lastIndexOf("/")+1, item.yunKey.length);
          imageList.push({name: name, url: self.yunPath+item.yunKey});
        });
        imageSizeModal(this, imageList); //图片尺寸提示
        var arr2 = Array.from(this.selectedFolderList);
        this.selectedFolderList = [];
        this.selectedFolderListIds = [];
        this.$emit('sureClicked',arr2 )
      },

      selectedFolder(folderItem){
        tiyData.tPage.currentPage = 1;
        tiyData.tParams.folderList.foderId = folderItem.id;
        tiyData.tParams.folderList.level = folderItem.level + 1;
        webFolderListByParentId(this, tiyData, folderItem);
      },
      selectedFolderForBar(folderItem){
        tiyData.tPage.currentPage = 1;
        tiyData.tParams.folderList.foderId = folderItem.id;
        tiyData.tParams.folderList.level = folderItem.level + 1;
        webFolderListByParentId(this, tiyData, folderItem);
      },
      uploadImageSuccess(response, file, fileList){
        webFolderListByParentId(this, tiyData, null);
        let self = this;
        if(response.success){
          response.result.forEach(function(item) {
            let name = item.yunKey.substring(item.yunKey.lastIndexOf("/")+1, item.yunKey.length);
            self.imageList.push({name: name, url: self.yunPath+item.yunKey});
          });
          if(this.imageListLength == this.imageList.length) { //全部上传完毕
            this.$Spin.hide(); //隐藏遮罩层
            imageSizeModal(this, this.imageList);
            this.imageList = []; //上传图片数组清空
            this.imageListLength = 0; //上传图片数组长度重设为0
          }
        } else {
            this.$Message.error('上传图片失败！' + response.errorMessage) ;
        }
      },
      uploadImageError(error, file, fileList){
        this.$Spin.hide();
      },
      webDelete(){
        webImageDelete(this, tiyData);
      },
      webAdd(){
        webImageAdd(this, tiyData, "addFolder");
      },
      addFolder(){
        tiyData.tParams.folder.name = '';
        tiyData.tStatus.modalFolder.isShow = true;
      },
      deleteItem(item){
        tiyData.tStatus.modalDelete.folder.objectIds.length=0;
        tiyData.tStatus.modalDelete.folder.objectIds.push(item.id);
        tiyData.tStatus.modalDelete.folder.type = '' != item.suffix ? 2 : 1;
        tiyData.tStatus.modalDelete.isShow = true;
        tiyData.tStatus.modalDelete.folder.name = item.name;
      },
      batchDeleteImages(){
        if (tiyData.tStatus.batchDelete.isBatch) {
          tiyData.tStatus.batchDelete.isBatch = false;
          tiyData.tStatus.batchDelete.title = '取消批量操作';
        } else {
          tiyData.tStatus.batchDelete.isBatch = true;
          tiyData.tStatus.batchDelete.title = '批量删除图片';
        }
      },
      uploadImageProgress(event, file, fileList){
        this.$Spin.show();
      },
      changeOrder(){
        tiyData.tPage.currentPage = 1;
        webFolderListByParentId(this, tiyData, null);
      },
      clickImage(item){
        //刷新一下数据 否则选择图片的div不会出现
        tiyData.tStatus.refreshChecked = false;
        if (tiyData.tStatus.isSingle) { //单选
            this.$ySpliceAll(tiyData.tData.selectedFolderList, this.selectedFolderList); //先全部清除
            if (!this.isImgSelected(item)) { // 切换已选
                this.$ySpliceAll(this.selectedFolderListIds);
                this.selectedFolderList.push(item);
                this.selectedFolderListIds.push(item.id);
            } else { //清除之前选中的
                this.$ySpliceAll(this.selectedFolderListIds);
            }
        } else { //多选
          if (!this.isImgSelected(item)) {
            // console.log("执行：添加");
            this.selectedFolderList.push(item);
            this.selectedFolderListIds.push(item.id);
          }else{
            // console.log("执行：删除");
            let index = this.selectedFolderListIds.indexOf(item.id);
            this.selectedFolderList.splice(index,1);
            this.selectedFolderListIds.splice(index,1);
          }
        }
        //刷新一下数据 否则选择图片的div不会出现
        tiyData.tStatus.refreshChecked = true;
      },
      isImgSelected(item){
       return this.selectedFolderListIds.yHas(item.id)
      },
        changeIsSingle() {
            if (tiyData.tStatus.isSingle) {
                this.$ySpliceAll(tiyData.tData.selectedFolderList);
            }
        },
      renderContent (h, {root, node, data}) {
        return h('span', {
          style: {
            display: 'inline-block',
          }
        }, [
          h('span',
            [
              h('Icon', {
                props: {
                  type: data.expand ? 'ios-folder' : 'ios-folder-outline',
                  size: 13
                },
                style: {
                  marginRight: '8px'
                }
              }),
              h('span', data.title)
            ]),
        ]);
      },
      changePage(page){
        tiyData.tPage.currentPage = page;
        webFolderListByParentId(this, tiyData, null);
      },
      sizeChange(p){
        tiyData.tPage.stepNumber = p;
        webFolderListByParentId(this, tiyData, null);
      },
      beforeUpload(image) {
        this.imageListLength++;
        return this.setImageSizeParams(image);
      },
      setImageSizeParams(file) {
        let self = this;
        return new Promise((resolve, reject) => {
          let fileReader = new FileReader();
          fileReader.onload = e => {
            let src = e.target.result;
            const image = new Image();
            image.onload = function () {
              tiyData.tParams.uploadParam.picSizes.splice(0);
              tiyData.tParams.uploadParam.picSizes.push({width: this.width, height: this.height});
              let requestMsg = ApiBase.createRequestMsg(tiyData.tParams.uploadParam);
              tiyData.tParams.uploadFolderParam = {requestMsg: JSON.stringify(requestMsg)}
              resolve();
            };
            image.onerror = reject;
            image.src = src;
          };
          fileReader.readAsDataURL(file);
        })
      },
    },

    mounted(){
    }
  }
</script>

<!--css样式-->
<style scoped lang="less">
@import  (once,optional)  "../css/base.less";

  .base_padding {
    padding: 0px;
    margin-bottom: 40px;
  }

  .modal_form_input {
    width: 200px;
    margin-right: 10px;
  }

  .demo-spin-icon-load {
    animation: ani-demo-spin 1s linear infinite;
  }

  @keyframes ani-demo-spin {
    from {
      transform: rotate(0deg);
    }
    50% {
      transform: rotate(180deg);
    }
    to {
      transform: rotate(360deg);
    }
  }


  .item_card{
    margin: 10px;
    text-align: center;
    /*border: solid #f1f1f1 1px;*/
    /*cursor: pointer;*/
    width: 180px;
    height: 170px;

    .item_folder{
      text-align: center;
      padding-top:0.5rem;
      display: -webkit-flex; /* Safari */
      display: flex;
      flex-direction: column;

      p{
        word-wrap:break-word;
        word-break:break-all;
        font-size: 0.75em;
        font-weight: 600;
        margin-top: 0.2rem;
    }

      .item_img_parent{
        height: 100px;
        text-align: center;
        img{
          max-height: 100px;
          max-width: 140px;
        }
      }

    }

    .item_select{
      position: absolute;
      right: 8px;
      top: 8px;
      margin: auto;
    }


  }





</style>
